import re
from xml.dom import minidom

def conll_transfer(in_path,out_path):
    out = open(out_path, 'w', encoding='utf-8')
    with open(in_path, 'r', encoding='GBK') as f:
        for line in f:
            if 'word' in line:
                line = re.findall(r'["](.*?)["]', line)
                line[3] = str(int(line[3]) + 1)
                if line[3] == '-1':
                    line[3] = str(int(line[0]) + 1)
                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_ \n"
                          .format(str(int(line[0]) + 1), line[1], line[1], line[2], line[2], line[3], line[4]))
            elif '/sent' in line:
                out.write(" \n")
    f.close()
    out.close()


def csv_transfer(in_path,out_path):
    out = open(out_path,'w',encoding='utf-8')
    with open(in_path,'r',encoding='utf-8') as f:
        for line in f:
            line = line.split('"')[1].split('$')
            for sentences in line:
                if '#' in sentences or "IHC" in sentences or "ER" in sentences or "免疫组化" in sentences:
                    continue
                else:
                    sentence = sentences.split("。")
                    for sent in sentence:
                        if sent:
                            if sent[-1] == ')' or sent[-1] =='.' or sent[-1] == '：' or  sent[-1] =='；':
                                out.write(sent.strip()+"\n")
                            elif sent != ' ':
                                out.write(sent.strip()+"。\n")
    f.close()
    out.close()


class Conll_transfer(object):
    def __init__(self):
        pass

    def xml_conll_transfer(self, in_path, out_path):
        # 使用minidom解析器打开 XML 文档
        fp = open(in_path, 'r', encoding="GBK")
        content = fp.read()
        fp.close()

        DOMTree = minidom.parseString(content)
        collection = DOMTree.documentElement
        sents = collection.getElementsByTagName('sent')
        results = []
        for sent in sents:
            ids = []
            conts = []
            poses = []
            parents = []
            relates = []
            id_parent_dic = {}
            words = sent.getElementsByTagName('word')
            length = len(words)

            record = []
            for i in range(0,length):
                id = int(words[i].getAttribute('id'))
                cont = words[i].getAttribute('cont')
                pos = words[i].getAttribute('pos')
                parent = int(words[i].getAttribute('parent'))
                relate = words[i].getAttribute('relate')
                ids.append(id)
                conts.append(cont)
                poses.append(pos)
                parents.append(parent)
                relates.append(relate)
                id_parent_dic[id] = parent
                print(ids)
                if "PUN" == relate:
                    if cont in ["“", "‘", "《", "（", "『"]:
                        record.append((id, cont, pos, parent, relate))
                        continue

                    elif cont in ["”", "’", "》", "）", "：", "，","』"]:

                        if len(parents) > 1:
                            if parents[-2] in ids:
                                parent = parents[-2]
                                print(parent)
                            else:
                                parent = id -1
                        else:
                            parent = id - 1
                    elif cont in ["。", "！", "？", "……"]:
                        for key in id_parent_dic:
                            if id_parent_dic[key] == -1:
                                parent = key
                    elif cont == '、':
                        if not relates:
                            parent = id - 2
                        else:
                            parent = id -1
                    else:
                        if len(words) -1 == id:
                            parent = id - 1
                        else:
                            parent = id + 1

                    ids = []
                    conts = []
                    poses = []
                    parents = []
                    relates = []
                record.append((id, cont, pos, parent, relate))

            results.append(record)

        print(len(results))
        out = open(out_path, 'w', encoding='utf-8')
        for record in results:
            for line in record:
                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_ \n"
                          .format(str(line[0] + 1), line[1], line[1], line[2], line[2], str(line[3] + 1), line[4]))
            out.write(" \n")
        out.close()

    def txt_conll_tansfer(self,in_path, out_path):
        out = open(out_path, 'w', encoding='utf-8')
        with open(in_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            length = len(lines)
            for i in range(0, length):
                line = lines[i].split('\t')
                if len(line) == 10:
                    if line[6] != "-1":
                        out.write(lines[i])
                    if line[1] == "（":
                        for j in range(i, length):

                            right_point = lines[j].split('\t')
                            if len(right_point) == 10:
                                if right_point[1] == "）":
                                    line[6] = right_point[6]
                                    out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                              .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                    break
                            elif len(right_point) == 1:
                                line[6] = str(int(line[0]) - 1)
                                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                            .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                break

                    if line[1] == "“":
                        for j in range(i, length):
                            right_point = lines[j].split('\t')
                            if len(right_point) == 10:
                                if right_point[1] == "”":
                                    line[6] = right_point[6]
                                    out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                              .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                    break
                            elif len(right_point) == 1:
                                line[6] = str(int(line[0]) - 1)
                                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                            .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                break

                    if line[1] == "‘":
                        for j in range(i, length):
                            right_point = lines[j].split('\t')
                            if len(right_point) == 10:
                                if right_point[1] == "’":
                                    line[6] = right_point[6]
                                    out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                              .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                    break
                            elif len(right_point) == 1:
                                line[6] = str(int(line[0]) - 1)
                                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                            .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                break

                    if line[1] == "《":
                        for j in range(i, length):
                            right_point = lines[j].split('\t')
                            if len(right_point) == 10:
                                if right_point[1] == "》":
                                    line[6] = right_point[6]
                                    out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                              .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                    break
                            elif len(right_point) == 1:
                                line[6] = str(int(line[0]) - 1)
                                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                            .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                break

                    if line[1] == "『":
                        for j in range(i, length):
                            right_point = lines[j].split('\t')
                            if len(right_point) == 10:
                                if right_point[1] == "』":
                                    line[6] = right_point[6]
                                    out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                              .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                    break
                            elif len(right_point) == 1:
                                line[6] = str(int(line[0]) - 1)
                                out.write("{}\t{}\t{}\t{}\t{}\t_\t{}\t{}\t_\t_\n"
                                            .format(line[0], line[1], line[2], line[3], line[4], line[6], line[7]))
                                break


                elif len(line) == 1:
                    out.write('\n')

        f.close()
        out.close()



transfer = Conll_transfer()
transfer.xml_conll_transfer('htp.xml','htp.txt')
transfer.txt_conll_tansfer('htp.txt','htp.conll')
#conll_transfer('htp.txt','htp.conll')
#csv_transfer('data/乳腺-1-11948_病理诊断数据.csv','data/乳腺病理诊断数据')
#xml_ransfer()